package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.dao.AddressBookDao;
import com.itheima.entity.AddressBook;
import com.itheima.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {


    @Autowired
    private AddressBookDao addressBookDao;

    @Override
    public Integer add(AddressBook addressBook) {
        addressBook.setCreateTime(LocalDateTime.now());
        addressBook.setUpdateTime(LocalDateTime.now());
        addressBook.setCreateUser(addressBook.getUserId());
        addressBook.setUpdateUser(addressBook.getUserId());

        return addressBookDao.insert(addressBook);
    }

    @Override
    public Integer setDefault(AddressBook addressBook) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, addressBook.getUserId());
        addressBook.setIsDefault(0);
        addressBookDao.update(addressBook, lqw); //根据userId 修改默认地址

        addressBook.setIsDefault(1); // 1 为默认地址
        return addressBookDao.updateById(addressBook); //根据id 修改默认地址
    }

   @Override
    public AddressBook get(Long id) {


        return addressBookDao.selectById(id);
    }

    @Override
    public AddressBook getDefault(AddressBook addressBook) {

        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook:: getUserId,addressBook.getUserId());
        lqw.eq(AddressBook::getIsDefault,1);

        return  addressBookDao.selectOne(lqw);
    }

    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,addressBook.getUserId());


        return addressBookDao.selectList(lqw);
    }

    @Override
    public void updateById(AddressBook addressBook) {

         addressBookDao.updateById(addressBook);

    }

    @Override
    public boolean removeByIds(List<Long> ids) {

        try {
            LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
            lqw.in(AddressBook::getId, ids);

            addressBookDao.delete(lqw);
        } catch (Exception e) {
            return false;
        }

        return true;
    }
}
